package com.acme.service.email;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.acme.domain.email.Email;
import com.acme.domain.email.Queue;
import com.acme.domain.email.impl.QueueImpl;

public class EmailService implements Runnable {

    private Queue queue = new QueueImpl();
    private static EmailService instance = new EmailService();

    public static EmailService getEmailService() {
	return instance;
    }

    public EmailService() {
	Thread thread = new Thread(this);
	thread.start();
    }

    public void close() {
	if (!queue.isClose()) {
	    queue.close();

	}

    }

    @Override
    public void run() {
	while (true) {
	    while (!queue.isEmpty()) {
		Email email = queue.getEmail();
		if (email == null) {
		    return;
		}
		sendEmail(email);
	    }
	    if (queue.isClose()) {
		return;
	    }
	    try {
		Thread.sleep(1000L);
	    } catch (InterruptedException ex) {
		Logger.getLogger(EmailService.class.getName()).log(
			Level.SEVERE, null, ex);
	    }
	}
    }

    public void sendNotificationEmail(final Email email) {

	queue.addEmail(email);
    }

    private void sendEmail(final Email email) {
	System.out.println(email);
    }
}
